<template>
  <div class="crop-category">
    <div class="page-header">
      <h2>农作物种类预览</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="分类名称">
          <el-input
            v-model="searchForm.categoryName"
            placeholder="请输入分类名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="分类编码">
          <el-input
            v-model="searchForm.categoryCode"
            placeholder="请输入分类编码"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="filteredData"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="true"
      >
        <el-table-column prop="categoryCode" label="分类编码" width="240" />
        <el-table-column prop="categoryName" label="分类名称" min-width="180" />
        <el-table-column prop="description" label="分类描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="parentName" label="父级分类" width="180" />
        <el-table-column prop="level" label="层级" width="120">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)">{{ row.level }}级</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 统计信息 -->
    <div class="statistics-area">
      <el-card shadow="never">
        <div class="statistics-content">
          <div class="stat-item">
            <span class="label">总分类数：</span>
            <span class="value">{{ totalCount }}</span>
          </div>
          <div class="stat-item">
            <span class="label">一级分类：</span>
            <span class="value">{{ level1Count }}</span>
          </div>
          <div class="stat-item">
            <span class="label">二级分类：</span>
            <span class="value">{{ level2Count }}</span>
          </div>
          <div class="stat-item">
            <span class="label">三级分类：</span>
            <span class="value">{{ level3Count }}</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import mockData from '@/utils/mockData'

// 响应式数据
const loading = ref(false)
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  categoryName: '',
  categoryCode: '',
  status: ''
})

// 计算属性
const filteredData = computed(() => {
  if (!searchForm.categoryName && !searchForm.categoryCode && !searchForm.status) {
    return tableData.value
  }

  const filterData = (data) => {
    return data.filter(item => {
      const matchesName = !searchForm.categoryName || 
        item.categoryName.toLowerCase().includes(searchForm.categoryName.toLowerCase())
      const matchesCode = !searchForm.categoryCode || 
        item.categoryCode.toLowerCase().includes(searchForm.categoryCode.toLowerCase())
      const matchesStatus = !searchForm.status || 
        item.status.toString() === searchForm.status

      if (item.children) {
        const filteredChildren = filterData(item.children)
        return (matchesName && matchesCode && matchesStatus) || filteredChildren.length > 0
      }
      
      return matchesName && matchesCode && matchesStatus
    }).map(item => {
      if (item.children) {
        return {
          ...item,
          children: filterData(item.children)
        }
      }
      return item
    })
  }

  return filterData(tableData.value)
})

// 统计信息计算属性
const totalCount = computed(() => {
  const countNodes = (data) => {
    return data.reduce((count, item) => {
      count++ // 当前节点
      if (item.children) {
        count += countNodes(item.children)
      }
      return count
    }, 0)
  }
  return countNodes(tableData.value)
})

const level1Count = computed(() => {
  return tableData.value.filter(item => item.level === 1).length
})

const level2Count = computed(() => {
  const countLevel2 = (data) => {
    return data.reduce((count, item) => {
      if (item.level === 2) count++
      if (item.children) {
        count += countLevel2(item.children)
      }
      return count
    }, 0)
  }
  return countLevel2(tableData.value)
})

const level3Count = computed(() => {
  const countLevel3 = (data) => {
    return data.reduce((count, item) => {
      if (item.level === 3) count++
      if (item.children) {
        count += countLevel3(item.children)
      }
      return count
    }, 0)
  }
  return countLevel3(tableData.value)
})

// 方法
const getLevelType = (level) => {
  const types = ['', 'success', 'warning', 'info']
  return types[level] || 'info'
}

const handleSearch = () => {
  // 搜索逻辑已经在 computed 中实现
  ElMessage.success('搜索完成')
}

const handleReset = () => {
  Object.assign(searchForm, {
    categoryName: '',
    categoryCode: '',
    status: ''
  })
  ElMessage.success('重置完成')
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = mockData
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.crop-category {
  padding: 20px;
  background: white;
  border-radius: 8px;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.table-area {
  margin-bottom: 20px;
}

.statistics-area {
  margin-top: 20px;
}

.statistics-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 16px 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.stat-item .label {
  color: #606266;
  font-size: 14px;
}

.stat-item .value {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-area .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
    width: 100%;
  }
  
  .search-area .el-form--inline .el-form-item .el-input,
  .search-area .el-form--inline .el-form-item .el-select {
    width: 100%;
  }
  
  .statistics-content {
    flex-direction: column;
    gap: 16px;
  }
}
</style>